import os

import akshare as ak

mainpath = os.path.dirname(os.path.dirname(__file__))


# 获取ETF基金清单
def get_etf_list():
    fund_list = ak.fund_etf_category_sina(symbol="ETF基金")
    path = os.path.join(mainpath, f'data/etf_list.csv')
    fund_list.to_csv(path,index=False, encoding='utf-8')


# 获取 ETF 基金数据
def get_fund_detail(etf_fund_code, down_path=''):
    fund_detail = ak.fund_etf_hist_sina(symbol=etf_fund_code)
    path = ''
    if down_path == '':
        path = os.path.join(mainpath, f'data/{etf_fund_code}.csv')
    if down_path == 'etfs':
        path = os.path.join(mainpath, f'data/etfs/{etf_fund_code}.csv')
    if down_path == 'lofs':
        path = os.path.join(mainpath, f'data/lofs/{etf_fund_code}.csv')

    fund_detail['fundname'] = etf_fund_code
    fund_detail.to_csv(path,index=False, encoding='utf-8')


def download_etf_fund():
    """
    sh510500 500etf
    sz159949 创业板50
    sh510310 沪深300
    sz159915 创业板

    """
    # 500ETF数据
    funds = [
        'sh510500','sh510300','sh512120','sh512010','sz159892','sz159859','sz002594','sh600276','sz000651'
    ]
    for fund in funds:
        get_fund_detail(fund)


def name_list(csv_name):
    import csv
    csv_f = os.path.join(mainpath, f'data/{csv_name}')
    fund_list = []
    with open(csv_f, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if not row['name'].startswith('N'):
                fund_list.append(row['symbol'])
            else:
                print(row['name'])
    return fund_list


if __name__ == '__main__':
    # 从akshare获取所有ETF列表清单  /data/etf_list.csv
    #get_etf_list()
    # 从akshare获取500etf  /data/etf_list.csv
    download_etf_fund()
